package cn.edu.njust.bio;

import cn.edu.njust.EchoClient;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

@Slf4j
public class BioEchoClient implements EchoClient {

    private Socket socket;

    private static String recv(Socket socket) {

        try {
            InputStream in = socket.getInputStream();
            // 这里用readAllBytes比较方便
            return new String(in.readAllBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    private static void send(Socket socket, String message) {
        try {
            OutputStream out = socket.getOutputStream();
            out.write(message.getBytes());
            // 发完消息记得关闭输出，否则会导致服务端read一直阻塞！(这里不采用拆包机制)
            socket.shutdownOutput();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void connect(int port) {
        socket = new Socket();
        try {
            socket.connect(new InetSocketAddress(port));
            log.info("连接服务器成功");
        } catch (IOException e) {
            log.error("连接服务器失败");
            e.printStackTrace();
        }
    }

    @Override
    public String echo(String message) {
        send(socket, message);
        log.info("发送消息{}给服务器", message);
        return recv(socket);
    }

    @Override
    public void close() {
        try {
            if (socket != null)
                socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
